import re
from .processor import Processor, GeneratorException


class Circulation(Processor):
    def __init__(self, list_dict: dict[str:list[dict]]):
        super().__init__("[@][{].*?[}]")
        self.list_dict = list_dict

    def sub(self, text) -> str:

        val = re.search(r'@\{(\w+)}', text)  # 取出类名
        val_list = re.findall(r'@\{\w+[.](\w+)}', text) # 取出属性
        if val:     # 如果可以取出类
            val = re.sub(r'\s', '', val.group(1)) # 清除所有类的空格
        else:
            return text
        s_list = []
        if val in self.list_dict:
            for i in self.list_dict[val]:
                s = text
                s = re.sub(r'@\{(\w+)}', '', s)
                for j in val_list:
                    s = re.sub(r'@\{' + val + '[.]' + j + '}', str(i[j]), s)
                s_list.append(s)
            return ''.join(s_list)
        elif val not in self.list_dict:
            raise GeneratorException('Circulation', '不存在变量')

        return text
